﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace EasyTCP
{
    public class EasyClient
    {

        #region preivate
        /// <summary> 不允许用户自己创建 </summary>
        private EasyClient( ) { }
        /// <summary> 唯一实例 </summary>
        static EasyClient p_instance = null;
        /// <summary> 唯一套接字 </summary>
        static Socket p_client = null;
        #endregion




        #region publish
        /// <summary> 编码格式 </summary>
        public static Encoding bufferEncoder = Encoding.Default;
        /// <summary> 共享Socket 不允许修改 </summary>
        public static Socket shareSocketInstance { get { return p_client; } }


        /// <summary> 当有接收到新的数据时调用 </summary>
        public static Action<string> onDataReceivedCallback;
        /// <summary> 当连接服务器成功时调用 </summary>
        public static Action onConnectServerSucceed;
        /// <summary> 当连接服务器失败时调用 </summary>
        public static Action onConnectServerFaild;
        /// <summary> 共享示例 不允许用户自行创建 </summary>
        public static EasyClient shareInstance
        {
            get
            {
                if ( p_instance == null )
                    p_instance = new EasyClient( );
                return p_instance;
            }
        }
        /// <summary> 启动客户端 ip格式案例: 127.0.0.1:5566 </summary>
        public static void Launch( string ip )
        {
            try
            {
                string[] address = ip.Split( ':' );
                IPEndPoint ep = new IPEndPoint( IPAddress.Parse( address[0] ), Convert.ToInt32( address[1] ) );

                p_client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
                p_client.Connect( ep );

                //服务器连接成功
                onConnectServerSucceed?.Invoke( );

                var T1 = new Thread( ( ) =>
                {

                    byte[] buffer = new byte[1024 * 1024];
                    while ( true )
                    {
                        int len = p_client.Receive( buffer, 0, buffer.Length, SocketFlags.None );
                        onDataReceivedCallback?.Invoke( bufferEncoder.GetString( buffer, 0, len ) );
                    }
                } );
                T1.IsBackground = true;
                T1.Start( );
            }
            catch ( Exception e )
            {
                Console.WriteLine( e.StackTrace );
                onConnectServerFaild?.Invoke( );
            }
        }
        /// <summary> 向服务器发送消息</summary>
        public static void Send(string data )
        {
            if(p_client.Connected) p_client.Send( bufferEncoder.GetBytes( data ) );
        }
        #endregion


    }

}
